package cn.lili.modules.share.serviceimpl;

import cn.hutool.core.util.StrUtil;
import cn.lili.cache.Cache;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.ResultUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.share.service.AppHmdService;
import cn.lili.modules.share.service.AppJiluService;
import cn.lili.modules.share.service.AppUserService;
import cn.lili.modules.share.service.ShareService;
import cn.lili.modules.share.entity.docs.AppUser;
import cn.lili.util.ToolsUtil;
import com.alibaba.fastjson.JSONObject;
import com.api.UserApi;
import com.pojos.OpenAppUser;
import com.pojos.UserShareBindRegister;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class ShareServiceImpl implements ShareService {

    private final UserApi userApi;
    private final AppUserService appUserService;
    private final AppJiluService appJiluService;
    private final AppHmdService appHmdService;
    private final Cache cache;

    /**
     * 获取分享二维码
     *
     * @return
     */
    @Override
    public ResultMessage<Object> getShareQrCode() {
        AuthUser authUser = UserContext.getCurrentUser();
        if (authUser == null || StrUtil.isEmpty(authUser.getOpenId())) {
            return ResultUtil.error(400, "未登陆");
        }
        return ResultUtil.data(authUser.getOpenId());
    }

    /**
     * @param sessionId
     * @param superior  父级openId
     * @return
     */
    @Override
    public ResultMessage<Object> apiUserLogin(String sessionId, String superior) {
        OpenAppUser openUser = userApi.getUserinfo(sessionId);
        if (openUser == null) {
            return ResultUtil.error(500, "获取飞语用户信息失败");
        }
        OpenAppUser parentOpenUser = userApi.getUserinfoByOpenId(superior);
        if (parentOpenUser == null) {
            return ResultUtil.error(500, "上级openid未找到飞语用户");
        }

        AppUser appUser = new AppUser();
        //List<AppUser> appUsers = appUserService.selectAppUserByOpenId(openUser.getOpenId());
        // 计算过期时间
        Long timeOut = System.currentTimeMillis() + (864008 * 30);
        appUser.setAccount(openUser.getAccount());
        appUser.setHead(openUser.getAvater());
        appUser.setZh(appUser.getAccount());
        appUser.setMobile(openUser.getMobile());
        appUser.setGender(openUser.getGender());
        appUser.setTime_out(timeOut.toString());
        appUser.setMobile(openUser.getMobile());
        appUser.setOpenid(openUser.getOpenId());
        appUser.setSuperior(superior);
        boolean resultFlag = appUserService.saveOrUpdate(appUser);
        //记录上级信息
        AppUser parentAppUser = new AppUser();
        parentAppUser.setAccount(parentOpenUser.getAccount());
        parentAppUser.setHead(parentOpenUser.getAvater());
        parentAppUser.setZh(parentOpenUser.getAccount());
        parentAppUser.setMobile(parentOpenUser.getMobile());
        parentAppUser.setGender(parentOpenUser.getGender());
        parentAppUser.setTime_out(timeOut.toString());
        parentAppUser.setMobile(parentAppUser.getMobile());
        parentAppUser.setOpenid(parentAppUser.getOpenid());
        appUserService.saveOrUpdate(parentAppUser);

        //未做排名
        //记录推广
        appJiluService.saveShareRecords(superior, appUser.getMobile());
        //String appId, String openId, String parentId, String token
        String appId = "fy_ds7d8s9ad7";

        String resultStr = userApi.setParentWithOutToken(appId, openUser.getOpenId(), parentOpenUser.getAccount());
        if (StrUtil.isNotEmpty(resultStr)) {
            JSONObject json = JSONObject.parseObject(resultStr);
            if (json.getInteger("code") == 200) {
                log.info("#apiUserLogin# 绑定成功,{}", resultStr);
                return ResultUtil.success();
            }
        }
        return ResultUtil.error();
    }


    /**
     * 分享注册并绑定上级
     * @param userShare
     * @return
     */
    @Override
    public ResultMessage<Object> shareRegisterAndBindParent(UserShareBindRegister userShare) {
        try {
            if (StrUtil.isNotEmpty(userShare.getParentOpenId()) && userShare.getParentOpenId().contains("#/")) {
                userShare.setParentOpenId(userShare.getParentOpenId().replaceAll("#/", ""));
            }
            JSONObject jsonObject = userApi.shareRegisterAndBindParent(userShare);
            if (jsonObject.getInteger("code") != 200) {
                return ResultUtil.error(400, jsonObject.getString("msg"));
            }
            // +1
            if (StrUtil.isNotEmpty(userShare.getParentOpenId())) {
                //appUser上级+1操作
                appUserService.updateOrSaveLowerTuiguang(userShare.getParentOpenId());
                //hmd表
                appHmdService.shareRegisterAddOneStatistics(userShare.getParentOpenId());
                //记录排行数据
                appJiluService.saveShareRecords(userShare.getParentOpenId(), userShare.getMobile());

            }
            String resultStr = jsonObject.get("data").toString();
            if(StrUtil.isNotEmpty(resultStr)){
                cache.put("shareParent" + userShare.getMobile(), userShare.getParentOpenId(), 1L, TimeUnit.HOURS);
                return ResultUtil.data(resultStr);
            }
        } catch (Exception e) {
            log.info("#shareRegisterAndBindParent# catch exception :{}", ToolsUtil.getExceptionSrintStackTrace(e));
            return ResultUtil.error(400, e.getMessage());
        }
        return ResultUtil.error();
    }



    /**
     * 分享注册账号设置密码
     * @param userShare
     * @return
     */
    @Override
    public ResultMessage<Object> shareRegisterSetPassword(UserShareBindRegister userShare, String session) {
        JSONObject jsonObject = userApi.shareRegisterSetPassword(userShare);
        if (jsonObject.getInteger("code") != 200) {
            return ResultUtil.error(400, jsonObject.getString("msg"));
        }
        String resultStr = jsonObject.get("data").toString();
        OpenAppUser openAppUser = userApi.getUserinfo(session);
        if (openAppUser != null) {
            //保存注册用户的信息
            appUserService.saveAppUser(openAppUser);
        }
        return ResultUtil.success();
    }


}
